using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using PluginHandler;
using PluginHandler.Database;

namespace DatabaseManager.Util.Executers
{
    /// <summary>
    /// Allows returning a database table schema as a DataTable, which can be displayed in the ChildQueryArea control.
    /// </summary>
    public class SchemaExecuter : IExecuter
    {
        private DbException _dbError;
        private DataTable _dataTable;
        private IDatabaseObject _databaseObject;

        /// <summary>
        /// Initializes a new instance of the <see cref="SchemaExecuter"/> class with the given database object.
        /// </summary>
        /// <param name="databaseObject">The database object.</param>
        public SchemaExecuter(IDatabaseObject databaseObject)
        {
            _databaseObject = databaseObject;
        }

        /// <summary>
        /// Gets the table schema of the given database object.
        /// </summary>
        /// <param name="databaseObject">The database object.</param>
        /// <returns></returns>
        public bool ExecuteQuery(IDatabaseObject databaseObject)
        {
            bool result = false;

            if (_databaseObject != databaseObject)
            {
                _databaseObject = databaseObject;
            }
            
            try
            {
                _dataTable = _databaseObject.GetTableSchema();

                result = true;
            }
            catch (DbException ex)
            {
                _dbError = ex;
                result = false;
            }

            return result;
        }

        #region IExecuter Member

        /// <summary>
        /// Gets the data table, which contains the schema of the database object.
        /// </summary>
        /// <value>The data table.</value>
        public DataTable DataTable
        {
            get { return _dataTable; }
        }

        /// <summary>
        /// Gets the <class cref="DbException"/>, if there has something been going wrong.
        /// </summary>
        /// <value>The database error.</value>
        public DbException DbError
        {
            get { return _dbError; }
        }

        /// <summary>
        /// Gets the table schema of the choosen database object in the DatabaseObject property.
        /// </summary>
        /// <returns></returns>
        public bool ExecuteQuery()
        {
            return ExecuteQuery(_databaseObject);
        }

        /// <summary>
        /// Gets the database object.
        /// </summary>
        /// <value>The database object.</value>
        public IDatabaseObject DatabaseObject
        {
            get { return _databaseObject; }
        }

        #endregion
    }
}
